package com.study.banyiyi.config;

import lombok.SneakyThrows;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @ClassName ZookeeperWatch
 * @Description zookeeper 分配至配置中心
 * @Author yangwm
 * @Date 2021/7/23 17:37
 * @Version 1.0
 */
public class ZookeeperWatch implements Watcher {

    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static ZooKeeper zk = null;
    private static Stat stat= new Stat();

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        //zookeeper配置数据存放位置
        String path = "/banyiyi";
        //连接zookeeper并注册一个默认的监听器
        zk = new ZooKeeper("127.0.0.1:2181", 5000, new ZookeeperWatch());
        //等待zk连接成功的通知
        countDownLatch.await();
        //获取配置目录的节点配置数据，并注册默认的监听器
        System.out.println(new String(zk.getData(path,true,stat)));

        Thread.sleep(50000);
    }

    @SneakyThrows
    @Override
    public void process(WatchedEvent watchedEvent) {
        if(Event.KeeperState.SyncConnected == watchedEvent.getState()){//监听zookeeper连接成功通知事件
            if(Event.EventType.None == watchedEvent.getType() && null == watchedEvent.getPath()){
                countDownLatch.countDown();
            }else if(watchedEvent.getType() == Event.EventType.NodeDataChanged){//目录节点发生变化
                System.out.println("配置已经更新，变为："+new String(zk.getData(watchedEvent.getPath(),true,stat)));
            }

        }
    }
}
